#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>  //errno
#include <string.h> //strerror()
#include <stdlib.h> //exit()
int main()
{
    pid_t id = fork();
    if (0 == id)
    {
        //child
        printf("I am a child process, pid:%d, ppid:%d\n", getpid(), getppid());
        int temp = 5;
        while (temp--)
        {
            printf("%d\r", temp+1);//倒计时
            fflush(stdout);//刷新标准输出流
            sleep(1);
        }
    }
    else if (id > 0)
    {
        //father
        //非阻塞轮询
        while (1)
        {
            int status = 0;//退出信息
            pid_t rid = waitpid(id, &status, WNOHANG);//非阻塞等待
            if (rid > 0)//等待成功, Z解除, 进程完全释放
            {
                if (WIFEXITED(status))
                {
                    //进程正常运行结束
                    printf("exit_code: %d\n", WEXITSTATUS(status));
                }
                else
                {
                    //异常终止
                    printf("exit_signal: %d\n", status & 0x7f);
                }
                break;
            }
            else if (rid == 0)//等待成功, 但进程还在运行
            {
                //空闲...
            }
            else //rid == -1
            {
                printf("errno: %d, strerror: %s\n", errno, strerror(errno));
                exit(-1);
            }
        }
    }
    else //id == -1
    {
        perror("fork");//创建失败
        exit(-1);
    }


    return 0;
}
